#include "stdTcpService.h"
#include <iostream>
using namespace std;
#include <json-c/json.h>
#include <cstring>
#include <unistd.h>

#define PORT 8080
#define BUFFER_SIZE 32

void registerFunc(StdTcpSocket &client)
{
    char username[BUFFER_SIZE];
    cout << "请输入用户名:";
    scanf("%s", username);

    char passwd[BUFFER_SIZE];
    cout << "请输入密码:";
    scanf("%s", passwd);

    /* 创建一个json对象 */
    json_object *jsonObj = json_object_new_object();
    json_object_object_add(jsonObj, "type", json_object_new_int(1));
    json_object_object_add(jsonObj, "username", json_object_new_string(username));
    json_object_object_add(jsonObj, "passwd", json_object_new_string(passwd));

    /* 将json对象转换成字符串 */
    const char *jsonStr = json_object_to_json_string(jsonObj);
    cout << "jsonObj : " << jsonStr << endl;
    client.sendMessage(jsonStr);

    /* 接收信息 */
    string recvData;
    client.recvMessage(recvData); 
    cout << "recvData :" << recvData << endl;

    //delete jsonObj;
}

void loginFunc(StdTcpSocket &client)
{
    char username[BUFFER_SIZE];
    cout << "请输入用户名:";
    scanf("%s", username);

    char passwd[BUFFER_SIZE];
    cout << "请输入密码:";
    scanf("%s", passwd);

    /* 创建一个json对象 */
    json_object *jsonObj = json_object_new_object();
    json_object_object_add(jsonObj, "type", json_object_new_int(2));
    json_object_object_add(jsonObj, "username", json_object_new_string(username));
    json_object_object_add(jsonObj, "passwd", json_object_new_string(passwd));

    /* 将json对象转换成字符串 */
    const char *jsonStr = json_object_to_json_string(jsonObj);
    //cout << "jsonObj : " << jsonStr << endl;
    client.sendMessage(jsonStr);

    /* 接收信息 */
    string recvData;
    client.recvMessage(recvData); 
    cout << "recvData :" << recvData << endl;

    //delete jsonObj;
}

int main()
{
    StdTcpSocket client;
    client.connectToServer("192.168.248.128", PORT);

    while(1)
    {
        int choice;
        cout<< "请输入:1.注册  2.登录" << endl ;
        cin >> choice;
        switch(choice)
        {
            case 1:
                registerFunc(client);
                break;
            case 2:
                loginFunc(client);
                break;
            default:
                break;
        }
        
    }
    

    return 0;
}